﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using MyClever.Lib;

namespace MyCleverMissionEditor
{
    public partial class PackageSheet : UserControl
    {
        public event EventHandler Toggled;

        private MissionPluginPackage packageToEdit;
        private SlotCollection slotCollection;
        
        public DataGridView DataGridView
        {
            get
            {
                return this.dataGridView1;
            }
        }

        public MissionPluginPackage PluginPackage
        {
            get
            {
                return this.packageToEdit;
            }
        }

        public SlotCollection SlotCollection
        {
            get
            {
                return this.slotCollection;
            }
        }

        public bool IsExpanded
        {
            get
            {
                return this.grpBxAddNewParameters.Visible;
            }
        }
        
        public PackageSheet(MissionPluginPackage package)
        {
            InitializeComponent();

            this.packageToEdit = package;

            this.lblPackageName.Text = String.Format("{0} - {1} Rows", this.packageToEdit.TableName, this.packageToEdit.Rows.Count);
            if (this.packageToEdit.Rows.Count > 0)
            {
                this.lblPackageName.BackColor = Color.Khaki;
            }

            this.CreateLayout();
        }

        /// <summary>
        /// For some reasons the column sizes of our datagridview1 is not correct in the constructor. So we must create our slotCollection here!
        /// </summary>
        private void PackageSheet_Load(object sender, EventArgs e)
        {
            this.slotCollection = new SlotCollection(this);
            this.dataGridView1.SizeChanged += new System.EventHandler(this.slotCollection.OnUpdate); 
        }

        public void Expand()
        {
            this.dataGridView1.Height = 90;
            this.grpBxAddNewParameters.Visible = true;
            this.ArrangeLayout();
        }

        public void Collapse()
        {
            // show header columns only!!
            this.dataGridView1.Height = this.dataGridView1.ColumnHeadersHeight;          
            this.grpBxAddNewParameters.Visible = false;
            this.ArrangeLayout();
        }

        public void Toggle()
        {
            if (true == this.IsExpanded)
            {
                this.Collapse();
            }
            else
            {
                this.Expand();
            }

            Debug.Assert(this.Toggled != null);
            this.Toggled(this, null);
        }

        private void ArrangeLayout()
        {
            int heightArrowsTop = (10 * this.dataGridView1.Columns.Count) + 30;
            int heightArrowsBottom = (10 * this.dataGridView1.Columns.Count) + 30;

            this.dataGridView1.Location = new Point(this.dataGridView1.Location.X, this.lblPackageName.Height + heightArrowsTop);
            this.grpBxAddNewParameters.Location = new Point(this.grpBxAddNewParameters.Location.X, this.lblPackageName.Height + heightArrowsTop + this.dataGridView1.Height + heightArrowsBottom);

            int height = this.lblPackageName.Height + heightArrowsTop + this.dataGridView1.Height + heightArrowsBottom;

            if (true == this.grpBxAddNewParameters.Visible)
            {
                height += +this.grpBxAddNewParameters.Height;
            }
            
            this.Size = new Size(this.Width, height);
        }

        private void lblPackageName_Click_1(object sender, EventArgs e)
        {            
            this.Toggle();
        }

        private int CreateColumnGuiElements(MissionPluginPackageColumn column, int posX, int posY)
        {
            if (column.DataType == typeof(bool))
            {
                posY = this.CreatePackageCheckbox(ref column, posX, posY);
            }
            else
            {
                posY = this.CreatePackageTextbox(ref column, posX, posY);
            }

            return posY;
        }

        private void CreateLayout()
        {
            // set the position of the data-groupBox
            this.dataGridView1.DataSource = this.packageToEdit;

            this.grpBxAddNewParameters.SuspendLayout();

            const int posX = 10;
            int posY = 20;
            int posXInputElements = -1;
            foreach (MissionPluginPackageColumn columnOn in this.packageToEdit.Columns)
            {
                // add label for the input gui-element
                Label lblPackageName = new Label();
                lblPackageName.Location = new Point(posX, posY);
                lblPackageName.Name = columnOn.ColumnName;
                lblPackageName.Size = new Size(110, 13);
                lblPackageName.Text = columnOn.ColumnName + ":";
                this.grpBxAddNewParameters.Controls.Add(lblPackageName);

                // calculate the x position of the gui-input element
                posXInputElements = posX + lblPackageName.Size.Width + 5;

                // create input gui-elements
                posY = this.CreateColumnGuiElements(columnOn, posXInputElements, posY) + 12;
            }

            this.btnAddPackageRow.Location = new Point(posXInputElements, posY);
            posY += this.btnAddPackageRow.Size.Height + 7;

            this.grpBxAddNewParameters.PerformLayout();
            this.grpBxAddNewParameters.Size = new Size(this.grpBxAddNewParameters.Size.Width, posY);

            this.grpBxAddNewParameters.ResumeLayout(true);
        }


        private int CreatePackageCheckbox(ref MissionPluginPackageColumn column, int posX, int posY)
        {
            CheckBox chBxColumnValue = new CheckBox();
            chBxColumnValue.Location = new Point(posX, posY);
            chBxColumnValue.Name = this.GetInputControlName(column);
            chBxColumnValue.AutoSize = true;
            chBxColumnValue.Size = new Size(85, 13);
            chBxColumnValue.Text = column.Description;
            this.grpBxAddNewParameters.Controls.Add(chBxColumnValue);

            return posY + chBxColumnValue.Size.Height;
        }

        private int CreatePackageTextbox(ref MissionPluginPackageColumn column, int posX, int posY)
        {
            TextBox txtBxColumnValue = new TextBox();
            txtBxColumnValue.Location = new Point(posX, posY);
            txtBxColumnValue.Name = this.GetInputControlName(column);
            txtBxColumnValue.Size = new Size(300, 20);
            txtBxColumnValue.Validating += new System.ComponentModel.CancelEventHandler(this.textBox_Validating);
            this.grpBxAddNewParameters.Controls.Add(txtBxColumnValue);

            // add advanced dialog button
            if (true == column.HasValidation)
            {
                Button addButton = new Button();
                addButton.Location = new Point(posX + txtBxColumnValue.Size.Width + 2, posY - 2);
                addButton.Name = "btnAdd";
                addButton.Size = new Size(15, 23);
                addButton.TabIndex = 2;
                addButton.Text = "+";
                addButton.UseVisualStyleBackColor = true;
                addButton.Tag = txtBxColumnValue;
                addButton.Visible = false;
                this.grpBxAddNewParameters.Controls.Add(addButton);

                if (true == column.Validation.ToLower().Contains("isfile"))
                {
                    addButton.Click += new System.EventHandler(this.StartFileBrowser);
                    addButton.Visible = true;
                }
                else if (true == column.Validation.ToLower().Contains("ispath"))
                {
                    addButton.Click += new System.EventHandler(this.StartFolderBrowser);
                    addButton.Visible = true;
                }
            }

            // add description for this textbox
            posY += txtBxColumnValue.Size.Height + 2;
            Label lblColumnDescription = new Label();
            lblColumnDescription.AutoSize = true;
            lblColumnDescription.Location = new Point(posX - 3, posY);
            lblColumnDescription.Name = column.ColumnName + "Description";
            lblColumnDescription.Size = new Size(85, 13);
            lblColumnDescription.Text = column.Description;
            lblColumnDescription.Font = new Font("Microsoft Sans Serif", 8);
            this.grpBxAddNewParameters.Controls.Add(lblColumnDescription);

            return posY + lblColumnDescription.Size.Height;
        }

        private string GetInputControlName(MissionPluginPackageColumn column)
        {
            return "INPUT_ELEMENT_" + column.ColumnName;
        }

        private bool IsInputControlName(string controlName, out string packageColumnName)
        {
            packageColumnName = "";
            if (true == controlName.StartsWith("INPUT_ELEMENT_"))
            {
                packageColumnName = controlName.Split('_')[2];
                return true;
            }
            return false;
        }

        private void textBox_Validating(object sender, CancelEventArgs e)
        {
            this.ValidateName((TextBox)sender);
        }

        private void ValidateName(TextBox textBox)
        {
            if (textBox.Text == "")
            {
                errorProvider1.SetError(textBox, "Please enter your Name");
            }
            else
            {
                errorProvider1.SetError(textBox, "");
            }
        }

        private void StartFolderBrowser(object sender, EventArgs e)
        {
            if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                Button columnAddBtn = (Button)sender;
                TextBox columnTxtBx = (TextBox)columnAddBtn.Tag;
                columnTxtBx.Text = this.folderBrowserDialog1.SelectedPath;
            }
        }

        private void StartFileBrowser(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Button columnAddBtn = (Button)sender;
                TextBox columnTxtBx = (TextBox)columnAddBtn.Tag;
                columnTxtBx.Text = this.openFileDialog1.FileName;
            }
        }

        private void btnAddPackageRow_Click(object sender, EventArgs e)
        {
            DataRow newPackageRow = this.packageToEdit.NewRow();

            // run through every control in the newParamter groupBox
            foreach (Control controlOn in this.grpBxAddNewParameters.Controls)
            {
                // is this a relevant input-gui element?
                string packageColumnName;
                if (this.IsInputControlName(controlOn.Name, out packageColumnName))
                {
                    if (typeof(TextBox) == controlOn.GetType())
                    {
                        TextBox textBox = (TextBox)controlOn;
                        newPackageRow[packageColumnName] = textBox.Text;
                    }
                    else //typeof(CheckBox)
                    {
                        CheckBox checkBox = (CheckBox)controlOn;
                        newPackageRow[packageColumnName] = checkBox.CheckState;
                    }
                }
            }
            this.packageToEdit.Rows.Add(newPackageRow);
            this.dataGridView1.Refresh();
        }
    }
}
